$(function () {
   var param = null;
    var pid = $.query.get("id");
    if(pid != null && pid.length != 0){
        param = "productId="+pid;
    }

    showShop(param);
});

/**
 * 购买/显示购物信息
 * @param param 参数
 */
function showShop(param) {
    $.post("/shop/buy",param,function (shopList) {
        var str = "";
        for(var i=0;i<shopList.length;i++){
            var obj = shopList[i];
            str += `<tr><td>${obj.product.name}</td><td>${obj.product.price}</td>
                <td>${obj.product.address}</td>
                    <td><input type="num" min="1" value="${obj.num}" onblur="updateNum(${obj.product.id},this.value)"></td>
                    <td>${obj.num * obj.product.price}</td>
                    <td><a href="javascript:removeProduct(${obj.product.id})">移除商品</a></td></tr>`;
        }
        $("#shopData").html(str);
        computTotalPrice();
    });
}

/**
 * 修改数量
 * @param productId 商品ID
 * @param num 新数量
 */
function updateNum(productId,num) {
    $.post("/shop/updateNum","productId="+productId+"&num="+num,function (info) {
        if(info =="ok"){
            showShop(null);
        }
    });
}

/**
 * 移除商品
 * @param productId 商品Id
 */
function removeProduct(productId) {
    $.post("/shop/remove","productId="+productId,function (info) {
       if(info == "ok"){
           showShop(null);
       }
    });
}
/**
 * 计算总价
 */
function computTotalPrice() {
    var totalPrice = 0;

    var list = $("#shopData tr");
    for(var i=0;i<list.length;i++){
        var itemPrice = $(list[i]).find("td")[4];
        totalPrice += parseInt($(itemPrice).html());
    }
    $("#totalSpan").html(totalPrice);
}

/**
 * 结帐
 */
function gotoOrder() {
    location.href="/html/user/order.html?total="+$("#totalSpan").html();
}